/**
 * DES加密解密
 * 安装：npm install crypto-js
 * "crypto-js": "^4.1.1",
 * 引入：import CryptoJS from 'crypto-js'
 */
import CryptoJS from "crypto-js";

type WordArray = CryptoJS.lib.WordArray;

/**
 * 密钥key生成方法
 */
/* 
function simpleRandomString() {
  return Math.random()
    .toString(36)
    .slice(2, 10)
    .replace(/[^a-z0-9]/gi, "")
    .split("")
    .map((c) => (Math.random() > 0.5 ? c.toUpperCase() : c))
    .join("");
} 
*/

/**
 * 密钥
 */
const keyHex: WordArray = CryptoJS.enc.Utf8.parse("G98FM76R");
const ivHex: WordArray = CryptoJS.enc.Utf8.parse("tgQgGVdK");
const option = { iv: ivHex, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 };

/**
 * DES加密
 * @param msg 要加密的数据
 * @returns {string} 返回加密后的数据
 */
export const encryptDES = (msg: string): string => {
  const encrypted = CryptoJS.DES.encrypt(msg, keyHex, option);
  const sign = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
  return sign;
};

/**
 * DES解密
 * @param ciphertext 要解密的数据
 * @returns {string} 返回解密后的数据
 */
export const decryptDES = (ciphertext: string): string => {
  if (ciphertext) {
    let decrypted = CryptoJS.DES.decrypt(ciphertext, keyHex, option);
    return decrypted.toString(CryptoJS.enc.Utf8);
  } else {
    return "";
  }
};

/**
 * AES加密
 */
export const encryptAES = (params: {
  data: any;
  type: string;
  param: string[];
  key: string;
}): any => {
  const { data, type, param } = params;
  const result = JSON.parse(JSON.stringify(data));
  if (type === "Base64") {
    param.forEach((ele) => {
      result[ele] = btoa(result[ele]);
    });
  } else {
    param.forEach((ele) => {
      var data = result[ele];
      const key = CryptoJS.enc.Latin1.parse(params.key);
      var iv = key;
      // 加密
      var encrypted = CryptoJS.AES.encrypt(data, key, {
        iv: iv,
        mode: CryptoJS.mode.CFB,
        padding: CryptoJS.pad.NoPadding,
      });
      result[ele] = encrypted.toString();
    });
  }
  return result;
};

/**
 * AES解密(CBC,Pkcs7)
 */
export const decryptAES = (word: string, str: string): string => {
  const key = CryptoJS.enc.Latin1.parse(str);
  var decrypt = CryptoJS.AES.decrypt(word, key, {
    iv: key,
    mode: CryptoJS.mode.CFB,
    padding: CryptoJS.pad.NoPadding,
  });
  //解密后，需要按照Utf8的方式将明文转位字符串
  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr;
};
